<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button
            v-allow="'Excel-push'"
            type="warning"
            size="small"
            @click="$router.push('/employees/import')"
          >导入excel</el-button>
          <el-button
            v-allow="'Excel-pull'"
            type="danger"
            size="small"
            @click="hExportExcel"
          >导出excel</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 10px">
        <el-table
          border
          :data="employees"
          :default-sort="{ prop: 'workNumber' }"
        >
          <el-table-column label="序号" type="index" :index="getIndex" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template slot-scope="scope">
              <span>{{ operatingTime(scope.row.timeOfEntry) }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/' + scope.row.id)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button
                v-allow="'del'"
                type="text"
                size="small"
                @click="del(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="end"
          style="height: 60px; margin-top: 15px"
        >
          <el-pagination
            background
            :page-sizes="[3, 5, 10]"
            :current-page.sync="curPage"
            :page-size="size"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 弹框 -->
    <el-dialog
      v-if="showDialog"
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <EmpDialog
        ref="AddEmployee"
        @close="close"
        @update-empolyee="hUpdateEmployee"
      />
    </el-dialog>

    <!-- 分配角色弹框 -->
    <el-dialog
      v-if="showDialogRole"
      title="分配角色"
      :visible.sync="showDialogRole"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <AssignRole :id="id" @close="hClose" />
    </el-dialog>
  </div>
</template>
<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './components/empDialog.vue'
import AssignRole from './assignRole.vue'

const obj = EmployeeEnum.hireType.reduce((item, b) => {
  item[b.id] = b.value
  return item
}, {})
export default {
  components: {
    EmpDialog,
    AssignRole
  },
  data() {
    return {
      page: 1,
      size: 5,
      employees: [],
      total: 0,
      curPage: 1,
      showDialog: false,
      showDialogRole: false,
      id: ''
    }
  },
  created() {
    this.loadEmployess()
  },
  methods: {
    async loadEmployess() {
      const res = await getEmployeesList(this.page, this.size)
      console.log(res)
      this.employees = res.data.rows
      this.total = res.data.total
      this.curPage = this.page
    },
    del(id) {
      this.$confirm('你确定要删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch((err) => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async doDel(id) {
      const res = await delEmployee(id)
      console.log(res)
      this.$message.success('删除成功')

      if (this.employees.length === 1) {
        this.page--
        if (this.page <= 0) {
          this.page = 1
        }
      }

      this.loadEmployess()
    },
    close() {
      this.showDialog = false
    },
    format(typeNum) {
      return obj[typeNum]
    },
    hUpdateEmployee() {
      this.showDialog = false
      if (this.total % this.size === 0) {
        this.page = this.total / this.size + 1
      } else {
        this.page = Math.floor(this.total / this.size) + 1
      }
      this.loadEmployess()
    },
    hCurrentChange(curPage) {
      this.page = curPage
      this.loadEmployess()
    },
    hSizeChange(curPage) {
      this.size = curPage
      this.loadEmployess()
    },
    getIndex(index) {
      return index + 1 + (this.page - 1) * this.size
    },
    // 时间戳
    operatingTime(timeDate) {
      return this.$moment(timeDate).format('YYYY-DD-MM')
    },
    formatDate(rows) {
      const mapList = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      const header = Object.keys(rows[0]).map((enkeys) => mapList[enkeys])
      const data = rows.map((obj) => {
        const key = obj['formOfEmployment'] // 1, 2
        console.log(key)
        obj['formOfEmployment'] = EmployeeEnum.hireType[key - 1].value // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })
      console.log(header, data)

      return { header, data }
    },
    async hExportExcel() {
      const res = await getEmployeesList(this.page, this.size)
      console.log(res)
      // this.formatDate(res.data.rows)
      const { header, data } = this.formatDate(res.data.rows)
      console.log(header, data)
      import('@/vendor/Export2Excel').then((excel) => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    hClose() {
      this.showDialogRole = false
    },
    hAssignRole(id) {
      this.showDialogRole = true
      this.id = id
    }
  }
}
</script>
